package com.changgou.seckill.mq;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author tang.qingbo
 * @Date 2020/9/9 20:59
 * @Version 1.0
 */
@Component
@RabbitListener(queues = "queueSeckillOrder")
public class SeckillOrderStatusListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 秒杀订单支付状态监听
     * @param message 监听到的消息
     */
    @RabbitHandler
    public void getPayStatus(String message) {
        System.out.println("message: " + message);

        //将监听到的消息转为map
        Map<String,String> resultMap = JSON.parseObject(message, Map.class);

        if ("SUCCESS".equalsIgnoreCase(resultMap.get("return_code"))) {
            //获取附加参数attach
            Map<String, String> attachMap = JSON.parseObject(resultMap.get("attach"), Map.class);

            //获取用户名
            String username = attachMap.get("username");

            if ("SUCCESS".equalsIgnoreCase(resultMap.get("result_code"))) {
                //说明支付成功 ====== 获取交易流水号
                String transactionId = resultMap.get("transaction_id");
                //修改订单状态
                seckillOrderService.updatePayStatus(username, transactionId);
            } else {
                //支付失败==>删除订单
                seckillOrderService.closeOrder(username);
            }
        }
    }
}
